package com.ws.client.utils;

import com.ws.client.other.InputSave;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpUtil {

    // 发送 HTTP POST 请求
    public static String sendPostRequest(String url, String data) throws Exception {
        URL requestUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        byte[] postData = data.getBytes(StandardCharsets.UTF_8);
        connection.getOutputStream().write(postData);

        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
        }

        return response.toString();
    }

    public static void sendQr(String qrContent, String qrIdent) throws Exception {

        LogHelper.debug(sendPostRequest(InputSave.remoteHost + "/system/wdata/add/computer", "{\n" +
                "    \"qrcontent\":\"" + qrContent + "\",\n" +
                "    \"agentcomputer\":\"" + InputSave.token_computer + "\",\n" +
                "    \"qrdent\":\"" + qrIdent + "\"\n" +
                "}"));
    }
}
